﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pf.Common
{
    /// <summary>
    /// A class for simulating dice rolls
    /// </summary>
    public class Dice
    {
        private Random _random;

        private Random Random
        {
            get 
            {
                if (_random == null)
                    _random = new Random();
                return _random;
            }
        }

        /// <summary>
        /// Reset the randomizer. Next roll will use a new seed.
        /// </summary>
        public void Reset()
        {
            _random = null;
        }

        /// <summary>
        /// Roll some dice.
        /// </summary>
        /// <param name="dieCount">The amount of dice to roll</param>
        /// <param name="dieSides">The sides on the dice</param>
        /// <returns></returns>
        public int Roll(int dieCount, int dieSides)
        {                       
            int total = 0;
            for (int i = 0; i < dieCount; i++)
            {
                total += Random.Next(1, dieSides + 1);
            }
            return total;
        }

        /// <summary>
        /// Roll some d6, then only add up the best three. Used mostly for ablity score rolls.
        /// </summary>
        /// <param name="dieCount">The amount of dice to roll</param>
        /// <returns></returns>
        public int BestThree(int dieCount = 4)
        {
            List<int> results = new List<int>();
            for (int i = 0; i < dieCount; i++)
            {
                var result = Roll(1, 6);
                if (results.Count < 3)
                {
                    results.Add(result);
                }
                else if (results.Any(r => result > r))
                {
                    results[results.IndexOf(results.Min())] = result;
                }
            }
            return results.Sum();
        }
    }
}
